use std::{
    io::{self, Write},
    path::PathBuf,
};


use crate::{client::{Client, ClientBuilder}, tormeta::TorMeta, tracker::Tracker};
pub struct App {
    file:Option<PathBuf>,
    client: Option<Client>,
    trackers: Vec<Tracker>,
}

fn display_tor(tor: &TorMeta) {
    println!("tracker: {}", tor.get_announce());
    println!("info hash: {}", tor.get_info_hash_str());
    println!("files: ",);
    for file in &tor.files() {
        println!("{}", file);
    }
}

impl App {
    pub fn new() -> Self {
        Self {
            file:None,
            client:None,
            trackers: Vec::<Tracker>::new(),
        }
    }
    pub fn list_tor_file(file: PathBuf) {
        if let Ok(tor) = TorMeta::from(file.clone()) {
            display_tor(&tor);
        } else {
            eprintln!("处理\"{}\"发生错误", file.to_string_lossy());
        }
    }
}

impl App {
    fn dispatch(&mut self, command: &str) -> Option<bool> {
        if command == "quit" {
            Some(false)
        } else if command == "list" {
            App::list_tor_file(self.file.as_ref().unwrap().clone());
            Some(true)
        } else if command == "init" {
            if let None = &self.client {
                let mut  client = ClientBuilder::new().build();
                let tor_meta = TorMeta::from(self.file.as_ref().unwrap().clone()).unwrap();
                self.trackers.push(Tracker::new(tor_meta.get_announce()));
                client.set_file(tor_meta);
                self.client = Some(client);
                println!("client 初始化完成");
            } else {
                println!("client 已初始化");
            }
            Some(true)
        } else if command == "peers" {
            if let Some(client) = self.client.as_mut() {
                client.fetch_peers(self.trackers.get(0).unwrap().clone());
            }
            Some(true)
        }  else {
            println!("未知命令{:?}", command);
            Some(true)
        }
    }

    pub fn interact(&mut self, file: PathBuf) {
        self.file = Some(file.clone());
        println!("互动模式");
        println!("当前文件: \"{}\"", file.clone().to_string_lossy());
        loop {
            print!("> ");
            io::stdout().flush().unwrap();
            let mut user_input = String::new();
            if let Ok(std_input) = io::stdin().read_line(&mut user_input) {
                let input = user_input.trim();
                if std_input > 0 {
                    if let Some(conti) = self.dispatch(input) {
                        if !conti {
                            break;
                        }
                    } else {
                        break;
                    }
                }
            }
        }
    }
}
